import React, { useEffect, useState, useRef } from 'react'
import { reqTags, reqUpdateTag, reqAddTag, reqDeleteTag } from '../../api'
import { Card, Button, Table, Space, Popconfirm, Modal, Form, Input, message } from "antd"


export function useDataSource(initDatasource) {
    const [total, setTotal] = useState(0)
    const [dataSource, setDataSource] = useState([])

    useEffect(() => {
        resetDatasource()
    }, [])

    async function resetDatasource() {
        const { result } = await initDatasource(1);
        const { records, total } = result;
        setTotal(total)
        setDataSource(records)
    }

    async function toPageReq(current) {
        const { result } = await initDatasource(current)
        setDataSource(result.records)
        setTotal(result.total)
    }

    function pageChange(current) {
        toPageReq(current)
    }

    return {
        dataSource,
        total,
        resetDatasource,
        pageChange
    }
}

function useTags() {
    const { dataSource, resetDatasource, total, pageChange } = useDataSource(reqTags)

    return {
        dataSource,
        resetDatasource,
        total,
        pageChange
    }
}

function useColumns(editFun, resetDatasource) {
    const columns = [
        {
            title: 'ID',
            dataIndex: 'id',
        },
        {
            title: '标签名',
            dataIndex: 'name',
        },
        {
            title: '操作',
            key: 'action',
            render: text => (
                <Space size="small">
                    <a onClick={() => {
                        editFun(text)
                    }}>编辑</a>
                    <Popconfirm
                        title="你确定要删除吗？"
                        onConfirm={() => confirm(text)}
                        okText="Yes"
                        cancelText="No"
                    >
                        <a >删除</a>
                    </Popconfirm>
                </Space>
            )
        },
    ];

    async function toDeleteTag(id) {
        const { success } = await reqDeleteTag(id)
        if (success) {
            message.success('删除成功')
            resetDatasource()
        }
    }

    function confirm({ id }) {
        toDeleteTag(id)
    }

    return {
        columns,
    }
}

export function useModal(form) {
    const [isEdit, changeIsEdit] = useState(false)
    const [isModalVisible, setIsModalVisible] = useState(false);

    const showModal = () => {
        setIsModalVisible(true);
    };

    function hiddenModal() {
        setIsModalVisible(false);
    }

    const handleCancel = () => {
        hiddenModal()
    }

    const handleOk = (updateFun, addFun) => {
        if (isEdit) {
            updateFun()
            return;
        }
        addFun()
    }

    const addFunction = () => {
        showModal()
        changeIsEdit(false)
        form.current.resetFields()
    }

    function editFun(text) {
        changeIsEdit(true)
        showModal()
        form.current.setFieldsValue(text)
    }

    return {
        isModalVisible,
        hiddenModal,
        isEdit,
        handleOk,
        handleCancel,
        editFun,
        addFunction
    };
}

function useTagForm(tagForm, resetDatasource, hiddenModal) {

    function toUpdateTag() {
        tagForm.current.validateFields().then(async value => {
            const { success } = await reqUpdateTag(value)
            if (success) {
                message.success('更新成功')
                resetDatasource()
                hiddenModal()
            }
        })
    }

    function toAddTag() {
        tagForm.current.validateFields().then(async value => {
            const { success } = await reqAddTag({ name: value.name })
            if (success) {
                message.success('添加成功')
                resetDatasource()
                hiddenModal()
            }
        })
    }

    return {
        toUpdateTag,
        toAddTag
    }

}


const Tags = () => {

    const tagForm = useRef()
    const { dataSource, resetDatasource, total, pageChange } = useTags()

    const { addFunction, isModalVisible, handleOk,
        handleCancel, isEdit, editFun,
        hiddenModal } = useModal(tagForm)

    const { toUpdateTag, toAddTag } = useTagForm(tagForm, resetDatasource, hiddenModal)
    const { columns } = useColumns(editFun, resetDatasource)

    return (
        <Card size="small"
            extra={<Button type="link" onClick={addFunction} >添加标签</Button>}
            style={{ width: '100%' }}>
            <Table dataSource={dataSource}
                columns={columns}
                pagination={{
                    defaultPageSize: 7, pageSize: 7,
                    showQuickJumper: true,
                    total: total, onChange: pageChange,
                    showTotal: (total) => `共 ${total} 条`
                }}
                size="small"
                rowKey="id" />
            <Modal title={isEdit ? '编辑标签' : '添加标签'}
                forceRender="true"
                destroyOnClose={true}
                visible={isModalVisible} onOk={() => {
                    handleOk(toUpdateTag, toAddTag)
                }} onCancel={handleCancel}>
                <Form
                    ref={tagForm}
                    name="basic"
                    labelCol={{
                        span: 5,
                    }}
                    wrapperCol={{
                        span: 16,
                    }}
                    preserve={false}
                >
                    <Form.Item
                        name="id"
                        hidden={true}
                    >
                        <Input />
                    </Form.Item>
                    <Form.Item
                        label="标签名"
                        name="name"
                        rules={[
                            {
                                required: true,
                                message: '请输入标签名',
                            },
                        ]}
                    >
                        <Input />
                    </Form.Item>
                </Form>
            </Modal>
        </Card>
    )
}

export default Tags
